import React, { useState } from "react";
import { Button, Progress, Typography, Dropdown, Menu, Modal, Input, ColorPicker } from "antd";
import { PlusOutlined, MoreOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { Droppable, Draggable } from "@hello-pangea/dnd";
import { useAppDispatch } from "../../../hooks/redux";
import { updateGroup, deleteGroup } from "../../../store/projectSlice";
import type { TaskGroup as TaskGroupType } from "../../../types/project";
import { TaskStatus } from "../../../types/project";
import TaskCard from "./TaskCard";
import CreateTaskModal from "./CreateTaskModal";

const { Title, Text } = Typography;

interface TaskGroupProps {
  group: TaskGroupType;
  projectId: string;
  taskFilters?: {
    search: string;
    status: string[];
    priority: string[];
    milestone: string[];
    startDate?: [string, string];
    dueDate?: [string, string];
  };
  taskSort?: {
    field: string;
    order: "asc" | "desc";
  };
  isDragDisabled?: boolean;
}

/**
 * 任务分组组件 - 显示一列任务卡片
 * 包含分组标题、进度条、任务列表、操作菜单等功能
 */
const TaskGroup: React.FC<TaskGroupProps> = ({
  group,
  projectId,
  taskFilters = {
    search: "",
    status: [],
    priority: [],
    milestone: [],
    startDate: undefined,
    dueDate: undefined
  },
  taskSort = {
    field: "createdAt",
    order: "desc"
  },
  isDragDisabled = false
}) => {
  const dispatch = useAppDispatch();
  const [createTaskVisible, setCreateTaskVisible] = useState(false);
  const [editGroupVisible, setEditGroupVisible] = useState(false);
  const [groupTitle, setGroupTitle] = useState(group.title);
  const [groupColor, setGroupColor] = useState(group.color || "#f5f5f5");

  /**
   * 筛选和排序任务
   */
  const getFilteredAndSortedTasks = () => {
    let filteredTasks = group.tasks.filter(task => {
      // 搜索筛选
      const matchesSearch =
        !taskFilters.search ||
        task.title.toLowerCase().includes(taskFilters.search.toLowerCase()) ||
        (task.description || "").toLowerCase().includes(taskFilters.search.toLowerCase());

      // 状态筛选
      const matchesStatus = taskFilters.status.length === 0 || taskFilters.status.includes(task.status);

      // 优先级筛选
      const matchesPriority = taskFilters.priority.length === 0 || taskFilters.priority.includes(task.priority);

      // 里程碑筛选
      const matchesMilestone =
        taskFilters.milestone.length === 0 || (task.milestone && taskFilters.milestone.includes(task.milestone));

      // 开始时间筛选
      const matchesStartDate =
        !taskFilters.startDate ||
        !task.startDate ||
        (new Date(task.startDate) >= new Date(taskFilters.startDate[0]) &&
          new Date(task.startDate) <= new Date(taskFilters.startDate[1]));

      // 截止时间筛选
      const matchesDueDate =
        !taskFilters.dueDate ||
        !task.dueDate ||
        (new Date(task.dueDate) >= new Date(taskFilters.dueDate[0]) &&
          new Date(task.dueDate) <= new Date(taskFilters.dueDate[1]));

      return (
        matchesSearch && matchesStatus && matchesPriority && matchesMilestone && matchesStartDate && matchesDueDate
      );
    });

    // 排序
    filteredTasks.sort((a, b) => {
      const aValue = a[taskSort.field as keyof typeof a];
      const bValue = b[taskSort.field as keyof typeof b];

      if (aValue == null) return 1;
      if (bValue == null) return -1;

      let comparison = 0;
      if (typeof aValue === "string" && typeof bValue === "string") {
        comparison = aValue.localeCompare(bValue);
      } else if (typeof aValue === "number" && typeof bValue === "number") {
        comparison = aValue - bValue;
      } else if (aValue instanceof Date && bValue instanceof Date) {
        comparison = aValue.getTime() - bValue.getTime();
      } else {
        comparison = String(aValue).localeCompare(String(bValue));
      }

      return taskSort.order === "desc" ? -comparison : comparison;
    });

    return filteredTasks;
  };

  const filteredTasks = taskSort.field === "manual" ? group.tasks : getFilteredAndSortedTasks();

  // 检查是否有筛选条件或拖拽被禁用
  const hasActiveFilters = Boolean(
    taskFilters.search ||
      taskFilters.status.length > 0 ||
      taskFilters.priority.length > 0 ||
      taskFilters.milestone.length > 0 ||
      taskFilters.startDate ||
      taskFilters.dueDate
  );

  const shouldDisableDrag = hasActiveFilters || isDragDisabled;

  /**
   * 计算分组内任务的完成进度
   * @returns 完成百分比 (0-100)
   */
  const calculateProgress = (): number => {
    if (filteredTasks.length === 0) return 0;
    const completedTasks = filteredTasks.filter(task => task.status === TaskStatus.COMPLETED);
    return Math.round((completedTasks.length / filteredTasks.length) * 100);
  };

  /**
   * 获取分组统计信息
   * @returns 包含各状态任务数量的统计对象
   */
  const getTaskStats = () => {
    const stats = {
      total: filteredTasks.length,
      notStarted: 0,
      inProgress: 0,
      completed: 0
    };

    filteredTasks.forEach(task => {
      switch (task.status) {
        case TaskStatus.NOT_STARTED:
          stats.notStarted++;
          break;
        case TaskStatus.IN_PROGRESS:
          stats.inProgress++;
          break;
        case TaskStatus.COMPLETED:
          stats.completed++;
          break;
      }
    });

    return stats;
  };

  /**
   * 处理分组编辑保存
   */
  const handleSaveGroup = () => {
    dispatch(
      updateGroup({
        projectId,
        groupId: group.id,
        data: {
          title: groupTitle,
          color: groupColor
        }
      })
    );
    setEditGroupVisible(false);
  };

  /**
   * 处理分组删除
   */
  const handleDeleteGroup = () => {
    Modal.confirm({
      title: "确认删除分组",
      content: `确定要删除分组 "${group.title}" 吗？分组内的任务将被移动到其他分组。`,
      okText: "确认删除",
      cancelText: "取消",
      okType: "danger",
      onOk: () => {
        dispatch(deleteGroup({ projectId, groupId: group.id }));
      }
    });
  };

  /**
   * 分组操作菜单
   */
  const groupMenu = (
    <Menu>
      <Menu.Item key="edit" icon={<EditOutlined />} onClick={() => setEditGroupVisible(true)}>
        编辑分组
      </Menu.Item>
      <Menu.Item key="delete" icon={<DeleteOutlined />} onClick={handleDeleteGroup} danger>
        删除分组
      </Menu.Item>
    </Menu>
  );

  const progress = calculateProgress();
  const stats = getTaskStats();

  return (
    <div className="flex-shrink-0 w-80 bg-gray-50 rounded-lg p-4">
      {/* 分组标题和操作 */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <div className="w-3 h-3 rounded-full" style={{ backgroundColor: group.color }} />
          <Title level={5} className="mb-0 text-gray-800">
            {group.title}
          </Title>
          <Text className="text-gray-500 text-sm">({stats.total})</Text>
        </div>
        <Dropdown overlay={groupMenu} trigger={["click"]}>
          <Button type="text" icon={<MoreOutlined />} className="text-gray-500 hover:text-gray-700" />
        </Dropdown>
      </div>

      {/* 进度条和统计 */}
      {stats.total > 0 && (
        <div className="mb-4">
          <div className="flex items-center justify-between mb-2">
            <Text className="text-sm text-gray-600">完成进度</Text>
            <Text className="text-sm font-medium text-gray-800">{progress}%</Text>
          </div>
          <Progress
            percent={progress}
            showInfo={false}
            strokeColor={{
              "0%": "#87d068",
              "100%": "#52c41a"
            }}
            className="mb-2"
          />
          <div className="flex justify-between text-xs text-gray-500">
            <span>未开始: {stats.notStarted}</span>
            <span>进行中: {stats.inProgress}</span>
            <span>已完成: {stats.completed}</span>
          </div>
        </div>
      )}

      {/* 筛选提示 */}
      {hasActiveFilters && (
        <div className="mb-3 p-2 bg-yellow-50 border border-yellow-200 rounded text-xs text-yellow-700">
          <span>⚠️ 筛选模式下拖拽功能已禁用，清空筛选条件后可正常拖拽</span>
        </div>
      )}

      {/* 拖拽禁用提示 */}
      {isDragDisabled && !hasActiveFilters && (
        <div className="mb-3 p-2 bg-blue-50 border border-blue-200 rounded text-xs text-blue-700">
          <span>🔄 任务移动中，请稍候...</span>
        </div>
      )}

      {/* 任务列表 - 拖拽容器 */}
      <Droppable droppableId={group.id} isDropDisabled={shouldDisableDrag}>
        {(provided, snapshot) => (
          <div
            ref={provided.innerRef}
            {...provided.droppableProps}
            className={`min-h-32 transition-colors ${
              snapshot.isDraggingOver ? "bg-blue-50 border-2 border-dashed border-blue-300" : ""
            }`}
          >
            {/* 渲染任务卡片 */}
            {shouldDisableDrag
              ? // 拖拽禁用模式：渲染任务，不可拖拽
                (hasActiveFilters ? filteredTasks : group.tasks).map(task => (
                  <div key={task.id} className="mb-3">
                    <TaskCard task={task} projectId={projectId} />
                  </div>
                ))
              : // 正常模式：渲染所有任务，可拖拽
                group.tasks.map((task, index) => (
                  <Draggable key={task.id} draggableId={task.id} index={index} isDragDisabled={shouldDisableDrag}>
                    {(provided, snapshot) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                        className={`mb-3 ${snapshot.isDragging ? "rotate-2 scale-105" : ""}`}
                        style={{
                          ...provided.draggableProps.style,
                          transform: snapshot.isDragging
                            ? `${provided.draggableProps.style?.transform} rotate(2deg)`
                            : provided.draggableProps.style?.transform
                        }}
                      >
                        <TaskCard task={task} projectId={projectId} />
                      </div>
                    )}
                  </Draggable>
                ))}

            {/* 如果没有筛选结果，显示提示 */}
            {filteredTasks.length === 0 && group.tasks.length > 0 && (
              <div className="text-center py-8 text-gray-500 text-sm">没有符合筛选条件的任务</div>
            )}
            {provided.placeholder}
          </div>
        )}
      </Droppable>

      {/* 新建任务按钮 */}
      <Button
        type="dashed"
        icon={<PlusOutlined />}
        onClick={() => setCreateTaskVisible(true)}
        className="w-full mt-4 border-gray-300 text-gray-600 hover:border-blue-400 hover:text-blue-500"
      >
        添加任务
      </Button>

      {/* 新建任务弹窗 */}
      <CreateTaskModal
        visible={createTaskVisible}
        onCancel={() => setCreateTaskVisible(false)}
        onSuccess={() => setCreateTaskVisible(false)}
        defaultGroupId={group.id}
        projectId={projectId}
      />

      {/* 编辑分组弹窗 */}
      <Modal
        title="编辑分组"
        open={editGroupVisible}
        onCancel={() => setEditGroupVisible(false)}
        onOk={handleSaveGroup}
        okText="保存"
        cancelText="取消"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">分组名称</label>
            <Input value={groupTitle} onChange={e => setGroupTitle(e.target.value)} placeholder="请输入分组名称" />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">分组颜色</label>
            <ColorPicker value={groupColor} onChange={color => setGroupColor(color.toHexString())} showText />
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default TaskGroup;
